package com.distribute.application.admin.finance;

import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;

import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.core.lang.*;
import com.distribute.framework.core.web.node.Export;
import com.distribute.framework.core.lang.Protocol.BeanFormat;
import com.distribute.framework.core.util.Excel;
import com.distribute.framework.core.util.Function;
import com.distribute.framework.core.web.util.*;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

import com.distribute.framework.model.*;
import com.distribute.application.admin.*;
import com.distribute.application.api.utils.Arith;
/************CTRL_CODE_INPORT************/
import com.distribute.application.api.utils.DateUtils;
import com.distribute.application.api.utils.IpUtil;
import com.distribute.application.api.utils.PayUtil;
import com.distribute.application.api.utils.wx.AuthUtil;
import com.distribute.application.api.utils.wx.CertHttpUtil;
import com.distribute.application.api.utils.wx.Config;
import com.distribute.application.api.utils.wx.SignUtils;
import com.distribute.application.api.utils.wx.WXPayUtil;
import com.distribute.application.utils.AlipyToUser;
import com.distribute.application.utils.WechatMouldUtil;
/************CTRL_CODE_INPORT************/


/**
 * 会员提现记录的Controller
 * @author 刘代应
 */
@SuppressWarnings({"unchecked","rawtypes"})
@flag("MembershipRecord")
@RestController
@Component(value="finance.MembershipRecordController")
public class MembershiprecordController{
	
	@limitVal(1)//查看权限
	@flag("stuct")
	@RequestMapping("/admin/finance/membershiprecord.list.do")
  	public Protocol list() {
  		try{
  			Protocol protocol = Protocol.create(true,null);
  			setFormDataInfo(protocol,null,null);
  			//处理页面的视图数据，比如显示哪些列，自定义显示列等
			ActionHelper.doPageViewFields(MembershipRecord.class);
  			Map<String,Object> params = setDefaultSort(ActionHelper.getQueryFormParams(MembershipRecord.class));
			protocol.set("PARAMS",ActionHelper.getQueryFormParams(MembershipRecord.class));
			protocol.set("fields", Utils.getRequest("fields"));
			
			
			
			
			Integer iPage = Utils.getInteger("page", 0);
			Integer iSize = Utils.getInteger("size",16);
			
			/************CTRL_BEFORE_LIST************/
			/************CTRL_BEFORE_LIST************/
			Page page = MembershipRecord.page(iPage,iSize,params);//调用获取分页
	    	protocol.setPage(page,new BeanFormat<MembershipRecord>(){
				public Map format(MembershipRecord t) {
					return t.toJSON();
				}
			});
			
			/************CTRL_AFTER_LIST************/
			/************CTRL_AFTER_LIST************/
			return protocol;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	@limitVal(32)//导出权限
	@flag("stuct")
	@RequestMapping("/admin/finance/membershiprecord.export.do")
  	public Protocol export(HttpServletResponse response) {
  		try{
  			Protocol protocol = Protocol.create(true,null);
  			setFormDataInfo(protocol,null,null);
  			//处理页面的视图数据，比如显示哪些列，自定义显示列等
			ActionHelper.doPageViewFields(MembershipRecord.class);
  			Map<String,Object> params = setDefaultSort(ActionHelper.getQueryFormParams(MembershipRecord.class));
  			params.put("idIn", Utils.getString("ids"));
			
			
			
			
			Integer iPage = Utils.getInteger("page", 0);
			Integer iSize = Utils.getInteger("size",16);
			
			/************CTRL_BEFORE_EXPORT************/
			/************CTRL_BEFORE_EXPORT************/
			final Map<String, Object> finalParams = params;
			//调用lazy3q.jar中的导出功能
			//参数说明：(这次导出多少条数据，到数据库查的时候一次查多少条，当前所在第几页,处理器，对应的模型类,要导出哪些字段)
			Utils.export(MembershipRecord.count(params).intValue(), 100, 0 , new Export(){//new Export这个类，他会根据参数分次查询，边查边写，目的只有一个，就是为了避免把大量的数据放在内存中
				@Override //重载实现Export的getPage方法，Export会分多次调用这个方法
				public Page getPage(Integer page, int size) {//这时的page和size是Export转化过后的当前页，每页查询数					
					return MembershipRecord.getMembershipRecordPage(page, size, finalParams);
				}
			}, MembershipRecord.class, Utils.getString("fields").split(","));
			
			/************CTRL_AFTER_EXPORT************/
			/************CTRL_AFTER_EXPORT************/
			
			return null;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	
  	
  	@limitVal(1)//查看权限
  	@flag("stuct")
  	@RequestMapping("/admin/finance/membershiprecord.get.do")
  	public Protocol get() {
  		try{
  			Protocol protocol = Protocol.create(true,null).set("membershipRecord",new HashMap());
  			MembershipRecord membershipRecord = Utils.getObject("", MembershipRecord.class);
  			if(membershipRecord!=null){
				protocol.set("membershipRecord",membershipRecord.toJSON());
			}
			Long id=Utils.or(Utils.getLong("id"),Utils.getLong("key"));
			String edittype = Utils.getString("edittype");
			
			if(id==null){
				
				
				
				setFormDataInfo(protocol,edittype,null);
				protocol.reset(false,null,"args-id-null");
			}else{
				
				membershipRecord=MembershipRecord.where.id(id).get();
				if(membershipRecord==null){
					return protocol.reset(false,"数据不存在","data-not-exist");
				}
				setFormDataInfo(protocol,edittype,membershipRecord);
				
				protocol.set("membershipRecord",membershipRecord.toJSON());
			}			
			
			
			if(Utils.equals(Utils.getString("edittype"), "check")){//表单[提现审核]
				
					
				/************LAZY3Q_FORM_UNDEFINE_提现审核************/
				/************LAZY3Q_FORM_UNDEFINE_提现审核************/
				
			}
			
				
			
			/************CTRL_CODE_GET************/
			/************CTRL_CODE_GET************/
			return protocol;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	  	
  	@limitVal(32)//导入权限
  	@RequestMapping("/admin/finance/membershiprecord.inport.do")
  	public Protocol inport(@RequestParam("file") final MultipartFile file) { 
  		try{
			final String requestToken = Utils.getString("membershipRecordToken");
			final Date lastToken = Utils.getSession(requestToken);
			if(lastToken==null || (new Date().getTime()-lastToken.getTime())>10000){
				if(requestToken!=null)Utils.setSession(requestToken,new Date());//放入Token时间戳	
				MembershipRecord.execute(new Function(){
					public <T> T execute(Object... arg0){
						
						/************CTRL_BEFOR_INPORT************/
						/************CTRL_BEFOR_INPORT************/
						MembershipRecord membershipRecord = Utils.getObject("membershipRecord", MembershipRecord.class);
						
						Excel excel = null;
						try {
							excel = Excel.parse(file.getInputStream(),file.getOriginalFilename());
						} catch (Exception e1) {
							e1.printStackTrace();
						}
						List<String> header = excel.getHeader(0);
						//检查列头信息是否正确
						{
							String[] array = Utils.getString("inport$").split(",");
							for(int j=0;j<header.size();j++){
								if(!Utils.equals(Utils.trim(array[j]),Utils.trim(header.get(j)))){
									throw new DefineException("列("+j+")头信息不正确");
								}
							}
						}
						List<List<String>> array = excel.getArray(0);
				        for(int i=0;i<array.size();i++){ 
							String[] inports = Utils.getString("inports").split(",");
							String sAll="";
							List<String> item = array.get(i);
				        	for(int j=0;j<inports.length;j++){
				        		try {
				        			sAll+=Utils.trim(item.get(j));
				        			MembershipRecord.class.getMethod("set"+Utils.ForMat(inports[j])+"$", String.class).invoke(membershipRecord, item.get(j));
				        		} catch (Exception e) {
									e.printStackTrace();
								}
				        	}
				        	if(Utils.empty(sAll))continue;
				        	//设置默认值
							setDefaultValue(membershipRecord,"insert");
				        	
							
								/************CTRL_BEFORE_INPORT************/
								/************CTRL_BEFORE_INPORT************/
							try{
								MembershipRecord.saveMembershipRecord(membershipRecord);			
								
								
							}catch(Exception ex){
								String strMessage = DefineException.parseException(ex,MembershipRecord.class);
								if(strMessage!=null){
									throw new DefineException(strMessage);
								}else{
									throw new DefineException(ex);
								}
							}
							
							/************CTRL_AFTER_INPORT************/
							/************CTRL_AFTER_INPORT************/
				        }
						
						//记录操作日志
						LoggerHelper.writeLog(MembershipRecord.class,"add","导入了[会员提现记录]数据",LoginHelper.getUserId(), membershipRecord,membershipRecord.getId());
						
						return null;
					}
				});
				
			}else{
				throw new DefineException("repeat-submit-error","对不起，请勿重复提交"+(10-((new Date().getTime()-lastToken.getTime())/1000))+"秒后再试");
			}
			
			/************CTRL_AFTER_INPORT************/
			/************CTRL_AFTER_INPORT************/
			return Protocol.create(true,"添加[会员提现记录]数据成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	
  	
  	@limitVal(2)//查看权限
  	@RequestMapping("/admin/finance/membershiprecord.insert.do")
  	public Protocol insert() {
  		try{
			final String requestToken = Utils.getString("membershipRecordToken");
			final Date lastToken = Utils.getSession(requestToken);
			if(lastToken==null || (new Date().getTime()-lastToken.getTime())>10000){
				if(requestToken!=null)Utils.setSession(requestToken,new Date());//放入Token时间戳	
				MembershipRecord.execute(new Function(){
					public <T> T execute(Object... arg0){
						
						/************CTRL_BEFOR_INSERT************/
						/************CTRL_BEFOR_INSERT************/
						MembershipRecord membershipRecord = Utils.getObject("membershipRecord", MembershipRecord.class);
						
						//批量插入处理
						String vValue = ""+(membershipRecord.getId()==null?"":membershipRecord.getId());
						String sArray[]={""+vValue};
						
						if(vValue.startsWith("[*]")){
							vValue=vValue.replace("[*]","");
							sArray=vValue.split("[\\s|\u3000|\\u00a0|,]+");		
						}
						
						for(String sItem:sArray){
							if(!Utils.empty(sItem))
							membershipRecord.setId(Long.valueOf(sItem));
							//设置默认值
							setDefaultValue(membershipRecord,"insert");
							
							
								/************CTRL_BEFORE_ADD************/
								/************CTRL_BEFORE_ADD************/
							MembershipRecord.saveMembershipRecord(membershipRecord);			
							
							
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
								
							
							
							
							
							
								/************CTRL_AFTER_ADD************/
								/************CTRL_AFTER_ADD************/
						}
						
						//记录操作日志
						LoggerHelper.writeLog(MembershipRecord.class,"add","添加了[会员提现记录]["+membershipRecord.getId()+"]",LoginHelper.getUserId(), membershipRecord,membershipRecord.getId());
						
						return null;
					}
				});
				
			}else{
				throw new DefineException("repeat-submit-error","对不起，请勿重复提交"+(10-((new Date().getTime()-lastToken.getTime())/1000))+"秒后再试");
			}
			
			/************CTRL_AFTER_INSERT************/
			/************CTRL_AFTER_INSERT************/
			return Protocol.create(true,"添加[会员提现记录]数据成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	@limitVal(4)//修改权限
  	@RequestMapping("/admin/finance/membershiprecord.update.do")
  	public Protocol update() {
  		try{
			final String requestToken = Utils.getString("membershipRecordToken");
			final Date lastToken = Utils.getSession(requestToken);
			if(lastToken==null || (new Date().getTime()-lastToken.getTime())>10000){
				if(requestToken!=null)Utils.setSession(requestToken,new Date());//放入Token时间戳	
				MembershipRecord.execute(new Function(){
					public <T> T execute(Object... arg0){
						
						/************CTRL_BEFOR_UPDATE************/
						/************CTRL_BEFOR_UPDATE************/
						MembershipRecord membershipRecord = Utils.getObject("membershipRecord", MembershipRecord.class);
						MembershipRecord oldMembershipRecord = null;
						String PARAMS = Utils.getString("PARAMS");
						String ids=Utils.getString("ids");
						if(!Utils.empty(PARAMS)){//根据查询条件批量更新
							Map params = Utils.eval(PARAMS);
							params.put("confirm", 1);
							params.put("definex","1=1");
							
							
							
								/************CTRL_BEFORE_UPDATE_BY************/
								/************CTRL_BEFORE_UPDATE_BY************/
							
							MembershipRecord.updateMembershipRecordByConfirm(ActionHelper.getSetValuesFromModel(membershipRecord), params);
							
							LoggerHelper.writeLog(MembershipRecord.class, "update", 
										"批量修改了[会员提现记录]",
										LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(null,membershipRecord,false)
										,null);
							
							
							/************CTRL_UPDATE_BY_PARAMS************/
							/************CTRL_UPDATE_BY_PARAMS************/
						}else if(!Utils.empty(ids)){//根据ids批量更新
							Map params = new HashMap();
							params.put("idIn",ids);
							params.put("confirm", 1);
							params.put("definex","1=1");
							
							MembershipRecord.updateMembershipRecordByConfirm(ActionHelper.getSetValuesFromModel(membershipRecord), params);
							
							LoggerHelper.writeLog(MembershipRecord.class, "update", 
										"批量修改了[会员提现记录]",
										LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(null,membershipRecord,false)
										,null);
							
							
							/************CTRL_UPDATE_BY_IDS************/
							/************CTRL_UPDATE_BY_IDS************/
						}else{
							if(Utils.empty(Utils.getString("all"))){//修改对象非空的字段
								
								oldMembershipRecord=MembershipRecord.where.id(membershipRecord.getId()).get();
								if(oldMembershipRecord==null){
									throw new DefineException("对不起，你没有权限修改当前数据");
								}
								
								
								/************CTRL_BEFORE_NOTNULL************/
								/************CTRL_BEFORE_NOTNULL************/
								
								MembershipRecord.updateMembershipRecord$NotNull(membershipRecord);
								
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
									
								
								
								
								
								LoggerHelper.writeLog(MembershipRecord.class, "update", 
										"修改了[会员提现记录]["+oldMembershipRecord.getId()+"]",
										LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(oldMembershipRecord, membershipRecord,false)
										,membershipRecord.getId());
								
								
								/************CTRL_UPDATE_NOT_NULL************/
								/************CTRL_UPDATE_NOT_NULL************/
							}else{//修改对象全部字段
								
								oldMembershipRecord=MembershipRecord.where.id(membershipRecord.getId()).get();
								if(oldMembershipRecord==null){
									throw new DefineException("对不起，你没有权限修改当前数据");
								}
								//设置默认值
								
									
									
								
									
									
								
									
									
								
									
									
								
									
									
								
									
									
								
									
									
									
								membershipRecord.setAlipayNo(oldMembershipRecord.getAlipayNo());	
									
								
									
									
								
									
									
								
									
									
								
									
									
								
									
									
								
									
									
								
									
									
								membershipRecord.setUpdateTime(oldMembershipRecord.getUpdateTime());	
									
								
									
									
								membershipRecord.setAddTime(oldMembershipRecord.getAddTime());	
									
								
									
									
								
								//设置默认值
								setDefaultValue(membershipRecord,"update");
								
															
								
								
								//从oldMembershipRecord同步membershipRecord未set过的值
								membershipRecord.mergeSet(oldMembershipRecord);
								
								
								/************CTRL_BEFORE_UPDATE************/
								/************CTRL_BEFORE_UPDATE************/
										
								MembershipRecord.updateMembershipRecord(membershipRecord);
								
								
								LoggerHelper.writeLog(MembershipRecord.class, "update", 
										"修改了[会员提现记录]["+oldMembershipRecord.getId()+"]",
										LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(oldMembershipRecord, membershipRecord,true)
										,membershipRecord.getId());
								
								
								/************CTRL_UPDATE_ALL************/
								/************CTRL_UPDATE_ALL************/
							}
						}
						
						/************CTRL_CODE_UPDATE************/
						/************CTRL_CODE_UPDATE************/
						return null;
					}
				});
				
			}else{
				throw new DefineException("repeat-submit-error","对不起，请勿重复提交"+(10-((new Date().getTime()-lastToken.getTime())/1000))+"秒后再试");
			}
			
			/************CTRL_AFTER_UPDATE************/
			/************CTRL_AFTER_UPDATE************/
			return Protocol.create(true,"修改[会员提现记录]数据成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	@limitVal(8)//删除权限
  	@RequestMapping("/admin/finance/membershiprecord.delete.do")
  	public Protocol delete() {
  		try{
			MembershipRecord.execute(new Function(){
				public <T> T execute(Object... arg0){
					Long pid=Utils.getLong("id");
					Long[] ids=new Long[]{pid};
					String strIds=Utils.getString( "ids");
					if(!Utils.empty(strIds) && !strIds.trim().equals("")){//批量删除
						String[] array = strIds.split(",");
						ids=new Long[array.length];
						for(int i=0;i<array.length;i++)
							ids[i]=Long.valueOf(array[i]);
					}
					if(ids.length==0){
						throw new DefineException("args-id-null","参数错误");
					}
					for(Long id:ids){
						MembershipRecord membershipRecord = null;
						
						membershipRecord=MembershipRecord.where.id(id).get();
						if(membershipRecord==null){
							throw new DefineException("对不起，你没有权限修改当前数据");
						}
						
						MembershipRecord.delete(id);						
						
						if(membershipRecord!=null)//记录操作日志
							LoggerHelper.writeLog(MembershipRecord.class,"del","删除了[会员提现记录]["+membershipRecord.getId()+"]",LoginHelper.getUserId(), membershipRecord);
						
						
						/************CTRL_CODE_DEL************/
						/************CTRL_CODE_DEL************/
					}
					return null;
				}
			});
			return Protocol.create(true,"删除操作成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	
  	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
		
	
  	
  	
  	

	/**
	 * 定义表单提现审核提交
	 */
	@limitVal(128)//提现审核权限
	@RequestMapping("/admin/finance/membershiprecord.check.do")
	public Protocol check(){
		try{
			Protocol protocol = Protocol.create(true);
			
			final String requestToken = Utils.getString("membershipRecordToken");
			final Date lastToken = Utils.getSession(requestToken);
			if(lastToken==null || (new Date().getTime()-lastToken.getTime())>10000){
				if(requestToken!=null)Utils.setSession(requestToken,new Date());//放入Token时间戳
				protocol = MembershipRecord.execute(new Function(){
					public <T> T execute(Object... arg0){
						MembershipRecord membershipRecord = Utils.getObject("membershipRecord", MembershipRecord.class);
						
						MembershipRecord dbMembershipRecord = null;
						
						dbMembershipRecord=MembershipRecord.where.id(membershipRecord.getId()).get();
						if(dbMembershipRecord==null){
							throw new DefineException("对不起，你没有权限修改当前数据");
						}
						
						
						//页面传入参数：membershipRecord.reasonsRefusal,
						
						//审核通过：
						if(Utils.equals(Utils.getString("membershipRecord.auditType"),"2")){
							
							/************CTRL_FORM_CODE_check_2************/
							if (dbMembershipRecord.getType()==(short)2) {
								 AlipyToUser alipyToUser=new AlipyToUser();	
		                            Account account=Account.where.member(dbMembershipRecord.getCashProvider()).get();
		                            System.out.println("dbMembershipRecord"+dbMembershipRecord.getMoney());
		                            Map<String,String> result = alipyToUser.alipay2User(dbMembershipRecord.getCallNo(), dbMembershipRecord.getMoney().toString(), account.getAlipayNo(), account.getAlipayName());//进行打款
				                           if (result.get("success")!=null&&result.get("success").equals("true")) {
				                        	   dbMembershipRecord.setErreoLog("打款成功");
				                        	   dbMembershipRecord.setAuditType((short)2);
				                        	   dbMembershipRecord.update();
						   						 WechatMouldUtil wechatMouldUtil=new WechatMouldUtil();
						   						 Map<String, Object> data=new HashMap<String, Object>();
						   						 Map<String, Object> data1=new HashMap<String, Object>();
						   						data1.put("value", dbMembershipRecord.getMoney());
						   						Map<String, Object> data2=new HashMap<String, Object>();
						   						data2.put("value", dbMembershipRecord.getUpdateTime$());
						   						data.put("keyword1", data1);
						   						data.put("keyword2", data2);
						   						TbMsg msg=new TbMsg(
						   							 	dbMembershipRecord.getCashProvider()//会员
						   							 	,"成功提现"+dbMembershipRecord.getMoney()//内容
						   							 	,new Date()//时间
						   								);
						   						msg.save();
										}else {
											TbMsg msg=new TbMsg(
					   							 	dbMembershipRecord.getCashProvider()//会员
					   							 	,"提现失败"//内容
					   							 	,new Date()//时间
					   								);
					   						msg.save();
					                         dbMembershipRecord.setErreoLog(result.get("des"));
					                         dbMembershipRecord.setAuditType((short)1);
					                         dbMembershipRecord.update();
										}
							}else {
								Member member=Member.where.uid(dbMembershipRecord.getCashProvider()).get();
								
								// 1.0 拼凑企业支付需要的参数
								String appid = AuthUtil.APPID; // 微信公众号的appid
								String mch_id = AuthUtil.MCHID; // 商户号
								String nonce_str = IpUtil.getRandomStringByLength(32); // 生成随机数
								String partner_trade_no = "wt"+dbMembershipRecord.getCashProvider()+""+new Date().getTime(); // 生成商户订单号
								String openid = member.getOpenid(); // 支付给用户openid
								String check_name = "NO_CHECK"; // 是否验证真实姓名呢
								String re_user_name = ""; // 收款用户姓名(非必须)
								BigDecimal df = new BigDecimal(dbMembershipRecord.getMoney()+"");
						     	df = df.multiply(new BigDecimal("100"));
						     	int fee = df.intValue();
								String amount = String.valueOf(fee); // 企业付款金额，最少为100，单位为分
								System.out.println("amount"+amount);
								String desc = "恭喜您，提现成功，钱已再您的微信账户中了！"; // 企业付款操作说明信息。必填。
								String spbill_create_ip = IpUtil.getIpAddr(Utils.getServletRequest()); // 用户的ip地址
								// 2.0 生成map集合
								SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>(); 
								packageParams.put("mch_appid", appid); // 微信公众号的appid
								packageParams.put("mchid", mch_id); // 商务号
								packageParams.put("nonce_str", nonce_str); // 随机生成后数字，保证安全性

								packageParams.put("partner_trade_no", partner_trade_no); // 生成商户订单号
								packageParams.put("openid", openid); // 支付给用户openid
								packageParams.put("check_name", check_name); // 是否验证真实姓名呢
								packageParams.put("re_user_name", re_user_name);// 收款用户姓名
								packageParams.put("amount", amount); // 企业付款金额，单位为分
								packageParams.put("desc", desc); // 企业付款操作说明信息。必填。
								packageParams.put("spbill_create_ip", spbill_create_ip); // 调用接口的机器Ip地址
								
								String sign  = SignUtils.creatSign("utf-8",packageParams);
								
								//4   封装退款对象
								packageParams.put("sign", sign);
								
								//5  将当前的map结合转化成xml格式
								String reuqestXml = WXPayUtil.getRequestXml(packageParams);
								System.out.println("请求xml---：");
								System.out.println(reuqestXml);
									// 6.0获取需要发送的url地址
									String wxUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; // 获取退款的api接口
									 
									
									System.out.println("发送前的xml为：" + reuqestXml);
									try {
									// 7,向微信发送请求转账请求
									String returnXml = CertHttpUtil.postData(wxUrl, reuqestXml, AuthUtil.MCHID, AuthUtil.CERTPATH);

									System.out.println("返回的returnXml为:" + returnXml);

									// 8，将微信返回的xml结果转成map格式
									Map<String, String> returnMap = PayUtil.doXMLParse(returnXml);
									if (returnMap.get("return_code").equals("SUCCESS")) {
										// 付款成功
										System.out.println("returnMap为:" + returnMap);
										membershipRecord.setErreoLog("打款成功");
					   						 WechatMouldUtil wechatMouldUtil=new WechatMouldUtil();
					   						 Map<String, Object> data=new HashMap<String, Object>();
					   						 Map<String, Object> data1=new HashMap<String, Object>();
					   						data1.put("value", dbMembershipRecord.getMoney());
					   						Map<String, Object> data2=new HashMap<String, Object>();
					   						data2.put("value", dbMembershipRecord.getUpdateTime$());
					   						data.put("keyword1", data1);
					   						data.put("keyword2", data2);
					   						TbMsg msg=new TbMsg(
					   							 	dbMembershipRecord.getCashProvider()//会员
					   							 	,"提现成功"+dbMembershipRecord.getMoney$()//内容
					   							 	,new Date()//时间
					   								);
					   						msg.save();
									}else {
										membershipRecord.setErreoLog("打款失败");
										membershipRecord.setAuditType((short)1);
										TbMsg msg=new TbMsg(
				   							 	dbMembershipRecord.getCashProvider()//会员
				   							 	,"提现失败"//内容
				   							 	,new Date()//时间
				   								);
				   						msg.save();
									}
								} catch (Exception e) {
									TbMsg msg=new TbMsg(
			   							 	dbMembershipRecord.getCashProvider()//会员
			   							 	,"提现失败"//内容
			   							 	,new Date()//时间
			   								);
			   						msg.save();
									membershipRecord.setErreoLog("打款失败");
									membershipRecord.setAuditType((short)1);
								}
							}
							//TODO:>2
							/************CTRL_FORM_CODE_check_2************/
						}
						
						//审核拒绝：
						if(Utils.equals(Utils.getString("membershipRecord.auditType"),"3")){
							
							/************CTRL_FORM_CODE_check_3************/
							 WechatMouldUtil wechatMouldUtil=new WechatMouldUtil();
	   						 Map<String, Object> data=new HashMap<String, Object>();
	   						 Map<String, Object> data1=new HashMap<String, Object>();
	   						data1.put("value", dbMembershipRecord.getMoney());
	   						Map<String, Object> data2=new HashMap<String, Object>();
	   						data2.put("value", DateUtils.formatDateTime(new Date()));
	   						Map<String, Object> data3=new HashMap<String, Object>();
	   						data3.put("value", "审核拒绝:"+membershipRecord.getReasonsRefusal());
	   						data.put("keyword1", data1);
	   						data.put("keyword2", data2);
	   						data.put("keyword3", data3);
	   						Member member=Member.where.uid(dbMembershipRecord.getCashProvider()).get();
	   						Account account=Account.where.member(member.getId()).get();
	   						account.setMoney(Arith.round(account.getMoney()+dbMembershipRecord.getMoney(), 2));
	   						account.update();
	   						TbMsg msg=new TbMsg(
	   							 	dbMembershipRecord.getCashProvider()//会员
	   							 	,"拒绝提现:"+membershipRecord.getReasonsRefusal()//内容
	   							 	,new Date()//时间
	   								);
	   						msg.save();
							/************CTRL_FORM_CODE_check_3************/
						}
						
						
						membershipRecord.update();
						
							
						LoggerHelper.writeLog(MembershipRecord.class, "modify", 
							"操作了[提现审核]["+dbMembershipRecord.getId()+"]",
							LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(dbMembershipRecord,membershipRecord,false)
							,dbMembershipRecord.getId());
							
						
						
						return null;
					}
				});
				
			}else{
				throw new DefineException("repeat-submit-error","对不起，请勿重复提交"+(10-((new Date().getTime()-lastToken.getTime())/1000))+"秒后再试");
			}
			 
			
			
			/************CTRL_FORM_RETURN_check************/
			/************CTRL_FORM_RETURN_check************/
			
			if(protocol!=null){
				return protocol;
			}
			
			
			return Protocol.create(true,"[提现审核]操作成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}

	

	@RequestMapping("/admin/finance/membershiprecord.query.do")
	public Protocol query(){
		try{
			Map<String,Object> params = setDefaultSort(ActionHelper.getQueryFormParams(MembershipRecord.class));
			
			
			
			
			
			String strTerm=Utils.getString("value");//智能搜索时的参数，一般都是主键后面那个字段
			if(!Utils.empty(strTerm)){
				if(strTerm.toLowerCase().startsWith("id:"))//如果查询条件以id:开头，则按ID查询
					params.put("id", strTerm.toLowerCase().replaceFirst("id:", ""));					
				else//按标识查询，模糊查询请带%
				{
					
					String strDefinex = "";
					
					strDefinex="(2=1 "+strDefinex+")";
					params.put("definex",strDefinex);
					
				}
			}
			
			Integer iSize = Utils.getInteger("size",10);
			
			
			/************CTRL_CODE_QUERY************/
			/************CTRL_CODE_QUERY************/
			
			List<MembershipRecord> list = MembershipRecord.page(0,iSize,params).getResult();
			
			Boolean bObject=Utils.getBoolean("object",false);//是否需要整个数据对象
			List<Map> result = new java.util.ArrayList();			
			for(MembershipRecord membershipRecord:list){
				Map map = new HashMap();
				map.put("key",membershipRecord.getId().toString());
				map.put("value", Utils.js(membershipRecord.getKeyValue()));
				if(bObject==true){
					map.put("object",membershipRecord.toJSON());
				}
				
				result.add(map);
			}
			
			
			
			/************CTRL_AFTER_QUERY************/
			/************CTRL_AFTER_QUERY************/
			
			return Protocol.create().setList(result);
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
  	
  	
	/************CTRL_DEFINE_CODE************/
	/************CTRL_DEFINE_CODE************/
  	
  	/**获取子项列表**/
	public static Map getItems(){
		Map map = new HashMap();
	
	
		
		/************CTRL_DEFINE_ITEMS************/
		/************CTRL_DEFINE_ITEMS************/
		return map;
	}
  	
  	/**
	* 设置排序
	**/
  	private Map<String,Object> setDefaultSort(Map<String, Object> params) {
		String strAsc=MembershipRecord.C.get(Utils.forMat(Utils.getString("asc")));//升序字段
		params.put("asc", strAsc);//放入查询条件
		String strDesc=MembershipRecord.C.get(Utils.forMat(Utils.getString("desc")));//降序字段
		params.put("desc",strDesc);//放入查询条件 
		if(Utils.empty(strAsc) && Utils.empty(strDesc))//如果未传入排序字段
			params.put("desc","id");//那么，默认以主键降序，传给Dao层
		return params;
	}
  	/**
	* 设置默认值
	**/
	public void setDefaultValue(MembershipRecord membershipRecord,String type){
		if(type.equals("insert")){//添加时
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			if(membershipRecord.getUpdateTime()==null)
				membershipRecord.setUpdateTime(new Date());
				
			
			if(membershipRecord.getAddTime()==null)
				membershipRecord.setAddTime(new Date());
				
			
			if(membershipRecord.getStatus()==null)
				membershipRecord.setStatus((short)1);
				
			
		}else if(type.equals("update")){//编辑时
			
			
			
			
			
			
			
			
			
			
			
			
			
			membershipRecord.setUpdateTime(new Date());
				
			
			
			
		}
	}
	 

	/**
	* 设置表单信息
	**/
	public void setFormDataInfo(Protocol protocol,String edittype,MembershipRecord membershipRecord){
		Map model = new HashMap();
		model.put("name","membershipRecord");
		model.put("caption","会员提现记录");
		model.put("type","table");
		model.put("icon","icon-jiagebaohu");
		model.put("PK","id");
		model.put("add",true);
		model.put("update",true);
		model.put("details",true);
		List propertys = new ArrayList();
		List submits = new ArrayList();
		model.put("propertys", propertys);
		model.put("submits", submits);	
		protocol.set("model", model);
		if(Utils.empty(edittype)){
		
			 
		
			 
		
			 
		propertys.add(Utils.add("name","type").add("cell","attr").add("caption","提现类型").add("input","select").add("primary",false).add("length",1).add("options",new Object[]{Utils.add("text","微信").add("value","1"),Utils.add("text","支付宝").add("value","2")}));  
			 
		
			 
		
			 
		
			 
		
			 
		
			 
		
			 
		propertys.add(Utils.add("name","auditType").add("cell","attr").add("caption","审核类型").add("input","select").add("primary",false).add("length",2).add("options",new Object[]{Utils.add("text","审核中").add("value","1"),Utils.add("text","已打款").add("value","2"),Utils.add("text","拒绝").add("value","3")}));  
			 
		
			 
		
			 
		propertys.add(Utils.add("name","clause").add("cell","attr").add("caption","条　　款").add("input","select").add("primary",false).add("length",2).add("options",new Object[]{Utils.add("text","同意").add("value","1"),Utils.add("text","不同意").add("value","2")}));  
			 
		
			 
		
			 
		
			 
		
			 
		
			 
		propertys.add(Utils.add("name","status").add("cell","coner").add("caption","状　　态").add("input","select").add("primary",false).add("length",2).add("options",new Object[]{Utils.add("text","正常").add("value","1"),Utils.add("text","无效").add("value","0")}));  
			 
		
		}
		
		
		else if(edittype.equals("check")){
			
			if(true  && (""+membershipRecord.getAuditType()).equals(""+1)){
			
				model.put("title","提现审核");
				
			
				propertys.add(Utils.add("name","name").add("caption","收款姓名").add("input","text").add("primary",false).add("length",32).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"readonly":"readonly")));
			

			
				propertys.add(Utils.add("name","cashCall").add("caption","提现电话").add("input","text").add("primary",false).add("length",32).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"readonly":"readonly")));
			

			
				propertys.add(Utils.add("name","cashProvider").add("caption","提 现 人").add("input","query").add("primary",false).add("length",8).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"readonly":"readonly")).add("relate","Member"));
			

			
				propertys.add(Utils.add("name","alipayNo").add("caption","支付宝账号").add("input","text").add("primary",false).add("length",32).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"readonly":"readonly")));
			

			
				propertys.add(Utils.add("name","money").add("caption","提现金额").add("input","menoy").add("primary",false).add("length",8).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"readonly":"readonly")));
			

			
				propertys.add(Utils.add("name","clause").add("caption","条　　款").add("input","select").add("primary",false).add("length",2).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"readonly":"readonly")).add("options",new Object[]{Utils.add("text","同意").add("value","1"),Utils.add("text","不同意").add("value","2")}));
			

			
				propertys.add(Utils.add("name","auditType").add("caption","审核类型").add("input","select").add("primary",false).add("length",2).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"readonly":"readonly")).add("options",new Object[]{Utils.add("text","审核中").add("value","1"),Utils.add("text","已打款").add("value","2"),Utils.add("text","拒绝").add("value","3")}));
			

			
				propertys.add(Utils.add("name","status").add("caption","状　　态").add("input","select").add("primary",false).add("length",2).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"readonly":"readonly")).add("options",new Object[]{Utils.add("text","正常").add("value","1"),Utils.add("text","无效").add("value","0")}));
			

			
				propertys.add(Utils.add("name","reasonsRefusal").add("caption","拒绝理由").add("input","text").add("primary",false).add("length",128).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			

				
					
				submits.add(Utils.add("name","membershipRecord.auditType").add("title","审核通过").add("value","2").add("icon","icon-libreoffice"));
					
				submits.add(Utils.add("name","membershipRecord.auditType").add("title","审核拒绝").add("value","3").add("icon","icon-libreoffice"));
					
				
			
			}else{
				protocol.setSuccess(false);
				protocol.setMessage("当前流程不在'提现审核'");
			}
			
		}
		
		
		else{
			
			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","callNo").add("caption","打款编号").add("input","text").add("primary",false).add("length",32).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","type").add("caption","提现类型").add("input","select").add("primary",false).add("length",1).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).add("options",new Object[]{Utils.add("text","微信").add("value","1"),Utils.add("text","支付宝").add("value","2")}));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","name").add("caption","收款姓名").add("input","text").add("primary",false).add("length",32).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","cashCall").add("caption","提现电话").add("input","text").add("primary",false).add("length",32).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","cashProvider").add("caption","提 现 人").add("input","query").add("primary",false).add("length",8).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).add("relate","Member"));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"none")).equals("none")){
				propertys.add(Utils.add("name","nikeName").add("caption","提现人名称").add("input","text").add("primary",false).add("length",32).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"none")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"readonly")).equals("none")){
				propertys.add(Utils.add("name","alipayNo").add("caption","支付宝账号").add("input","text").add("primary",false).add("length",32).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"readonly")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","money").add("caption","提现金额").add("input","menoy").add("primary",false).add("length",8).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","auditType").add("caption","审核类型").add("input","select").add("primary",false).add("length",2).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).add("options",new Object[]{Utils.add("text","审核中").add("value","1"),Utils.add("text","已打款").add("value","2"),Utils.add("text","拒绝").add("value","3")}));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","reasonsRefusal").add("caption","拒绝理由").add("input","text").add("primary",false).add("length",128).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","clause").add("caption","条　　款").add("input","select").add("primary",false).add("length",2).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).add("options",new Object[]{Utils.add("text","同意").add("value","1"),Utils.add("text","不同意").add("value","2")}));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","formid").add("caption","formId").add("input","text").add("primary",false).add("length",32).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","erreoLog").add("caption","打款日志").add("input","text").add("primary",false).add("length",2000).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"none")).equals("none")){
				propertys.add(Utils.add("name","updateTime").add("caption","修改时间").add("input","datetime").add("primary",false).add("length",19).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"none")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"none")).equals("none")){
				propertys.add(Utils.add("name","addTime").add("caption","添加时间").add("input","datetime").add("primary",false).add("length",19).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"none")));
			}

			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"editable")).equals("none")){
				propertys.add(Utils.add("name","status").add("caption","状　　态").add("input","select").add("primary",false).add("length",2).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"editable")).add("options",new Object[]{Utils.add("text","正常").add("value","1"),Utils.add("text","无效").add("value","0")}));
			}

			submits.add(Utils.add("name","submiter").add("value","完成").add("title","完成").add("icon","icon-weibiaoti8"));
		}
	}
  
}